//
//  OTAUpdateFirmwareNordicVc.m
//  project
//
//  Created by 黄建华 on 2018/3/27.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "OTAUpdateFirmwareNordicVc.h"
#import "AppDelegate.h"
#import "FileModelEntity.h"
#import "DownloadEntity.h"
#import "SydOTA.h"
#import "Utility.h"
@interface OTAUpdateFirmwareNordicVc ()
@property (nonatomic, assign) BOOL isUpdateIng;
@property (nonatomic, assign) BOOL updateFirmwareFinish;
@property (nonatomic, assign) BOOL delayUpdateButton;

@end

@implementation OTAUpdateFirmwareNordicVc

- (void)showProgress {
    if (_showView) {
        [_showView removeFromSuperview];
        _showView = nil;
    }
    _showView = [[OTAShowView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH -80, 150)];
    [_showView showViewProgress];
    _showView.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);
    [self.view addSubview:_showView];
    //    [_showView popupWithtype:PopupViewOption_blur succeedBlock:^(UIView *View)
    //     {
    //         View.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);
    //     } dismissBlock:^(UIView *View)
    //     {
    //     }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    DEF_WEAKSELF_(OTAUpdateFirmwareNordicVc)
    [KKBLEDFUHelper sharedInstance].updateBlock = ^(KKBLEDFUHelperUpdateStatus state, NSInteger number) {
        [weakSelf updateWareUpdateStatus:state percent:number];
    };
}

- (void)updateWareUpdateStatus:(KKBLEDFUHelperUpdateStatus)state percent:(NSInteger)percent {
    if (state == KKBLEDFUHelperUpdateing) {
        _showView.progressLabel.text = [NSString stringWithFormat:@"%d %%", percent];
        [self updateFirmware:percent];
        self.isUpdateIng = YES;
    } else if (state == KKBLEDFUHelperUpdateSuccess) {
        [KK_BLEConnect firmWareUpdateEnd:YES];
        [self updateFirmSuccess];
        _showView.progressLabel.text = [NSString stringWithFormat:@"100 %%"];
        self.isUpdateIng             = NO;
    } else if (state == KKBLEDFUHelperUpdateFail) {
        self.isUpdateIng                = NO;
        _showView.progressView.progress = 0.0;
        [KK_BLEConnect firmWareUpdateEnd:NO];
        [self updateFail];
    } else if (state == KKBLEDFUHelperNoUpdate) {
        self.isUpdateIng                = NO;
        _showView.progressView.progress = 0.0;
    }
}

- (void)updateFail {
    if (_isUpdateIng) {
        SHOWMBProgressHUD(HHH_Text(@"Upgrade failed"), nil, nil, NO, 2.0);
    }
    _updateFirmwareFinish = NO;
    
    _isUpdateIng                    = NO;
    _showView.progressView.progress = 0;
    _showView.progressLabel.text    = @"0";
    
    [_showView removeFromSuperview];
    _showView = nil;
}

// 升级成功
- (void)updateFirmSuccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"恭喜你,升级成功!")
                                                    message:@"" delegate:self
                                          cancelButtonTitle:nil
                                          otherButtonTitles:SN_Text(@"确定"), nil];
    
    alert.tag = 2;
    [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
    [alert show];
    
    _updateFirmwareFinish = YES;
    _isUpdateIng          = NO;
    _showView.progressView.progress = 1.0;
    _showView.progressLabel.text    = @"100";
    //    [self performSelector:@selector(FinishPushMainView) withObject:nil afterDelay:2.5];
}

- (void)FinishPushMainView {
    [kK_App enterMainVc];
}

- (void)updateFirmware:(NSInteger)percent {
    _showView.progressView.progress = percent * 1.0/ 100;
//    NSLog(@"固件升级进度>>>>>>>%d %%", percent);
}

- (void)btnClick {
    if (_isUpdateIng == NO && _delayUpdateButton == NO) {
        if (KK_BLEModel.bleOnlineVersion > KK_BLEModel.bleVersion) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"新的设备固件更新")
                                                            message:SN_Text(@"检测到您的设备有新的固件更新,确定更新吗?") delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:SN_Text(@"取消"), SN_Text(@"更新"), nil];
            alert.tag = 1;
            [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
            [alert show];
        } else {
            SHOWMBProgressHUD(nil, SN_Text(@"当前已为最新版本"), nil, NO, 2.0);
        }
    } else {
        SHOWMBProgressHUD(HHH_Text(@"Is currently upgrading! Please wait ..."), nil, nil, NO, 2.0);
    }
}

- (void)updateFirmwareClick {
    if (KK_ShareData.isDown) {
        if (![DownloadEntity sharedInstance].filePath) {
            SHOWMBProgressHUD(HHH_Text(@"No upgrade file"), nil, nil, NO, 2.0);
            [[FileModelEntity sharedInstance] checkUpdateFirmwareInfo];
            return;
        }
        NSLog(@"下载升级包成功 开始连接升级>>>>>>>>>>>>");
    } else {
        SHOWMBProgressHUD(HHH_Text(@"No upgrade file"), nil, nil, NO, 2.0);
        [[FileModelEntity sharedInstance] checkUpdateFirmwareInfo];
        return;
    }
    
    if (_showView.progressView.progress > 0.01) {
        SHOWMBProgressHUD(HHH_Text(@"Is currently upgrading! Please wait ..."), nil, nil, NO, 2.0);
        return;
    }
    
    if (_delayUpdateButton == NO) {
        if ([KK_BLEModel.chip containsString:@"nrf"]) {
            [KK_BLEConnect startUpdateFirmWare];
        } else {
            [KK_BLESend resetSendCMD];
            NSURL  *url = [Utility getUpdateFirmWareDailogPath];
            SydOTA *syd = [[SydOTA alloc]init];
            [syd OTA_START:@"FF01" data:url.absoluteString];
            DEF_WEAKSELF_(OTAUpdateFirmwareNordicVc)
            syd.sydotaProgressBlock = ^(NSInteger index) {
                [weakSelf performSelector:@selector(delayUPdateView:) withObject:StrByInt(index) afterDelay:1.0];
            };
        }
        
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(onceClickUpdateButton) object:nil];
        [self performSelector:@selector(onceClickUpdateButton) withObject:nil afterDelay:5.0];
        _isUpdateIng       = YES;
        _delayUpdateButton = YES;
    }
}

- (void)delayUPdateView:(NSString *)indexS {
    NSInteger index = indexS.integerValue;
    
    _showView.progressView.progress = index * 1.0/ 100;
    _showView.progressLabel.text    = [NSString stringWithFormat:@"%d", index];
    if (index == 100) {
        [self performSelector:@selector(updateFinishLastInfo) withObject:nil afterDelay:5.0];
    }
}

- (void)updateFinishLastInfo {
    [self updateFirmSuccess];
}

- (void)delayShow {
    [self performSelector:@selector(onceClickUpdateButton) withObject:nil afterDelay:2.0];
}

- (void)onceClickUpdateButton {
    [self showProgress];
    _delayUpdateButton = NO;
}

- (void)beginUpdaetFirmwareTimeOut {
    if (!_updateFirmwareFinish) {
        SHOWMBProgressHUD(HHH_Text(@"Upgrade timeout"), nil, nil, NO, 2.0);
        _isUpdateIng              = NO;
        KK_BLEConnect.isUpdateing = NO;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //开始
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            if ([KK_BLEModel.chip containsString:@"nrf"]) {
                [self updateFirmwareClick];
            } else if ([KK_BLEModel.chip containsString:@"syd"]) {
                [self updateFirmwareClick];
            }
        }
    }
    //完成
    if (alertView.tag == 2) {
        [self FinishPushMainView];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _isUpdateIng = NO;
}

- (void)leftbuttonClick {
    if (_isUpdateIng == NO && _delayUpdateButton == NO) {
        KK_BLEConnect.isUpdateing = NO;
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        SHOWMBProgressHUD(HHH_Text(@"Is currently upgrading! Please wait ..."), nil, nil, NO, 2.0);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

